<?php

namespace App\Http\Controllers\WorkProject\JbhDev;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Log;

class ProjectController extends Controller
{
    protected $remoteDB = 'mysql_jbh_dev';
    protected $localDB = 'mysql_jbh_local';
    //测试环境表与本地表对比
    public function compareRemoteWithLocal(){
        $res = DB::connection($this->remoteDB)->select('show tables');
        $local = DB::connection($this->localDB)->select('show tables');
        $resDiff = collect($res)->map(function($value){
            $value = (array)($value);
            $value = reset($value);
            if(!strpos($value,'copy1')){
                return str_replace(' ','',$value);
            }
        })->diff(collect($local)->map(function($value){
            $value = (array)($value);
            return str_replace(' ','',reset($value));
        }));
        return $resDiff;

    }

    //同步远程端到本地数据表数量
    public function synchronizeTable(){
        $resDiff = $this->compareRemoteWithLocal();
        foreach($resDiff as $value){
            if(is_null($value)){
                continue;
            }
            $sqlForCreate = $this->getCreateTableSqlByTableName($value);
            if(is_string($sqlForCreate)){
                $this->createTableBySql($sqlForCreate);
                Log::info($value.'已经执行创建');
            }
        }
    }

    //获取建表语句
    public function getCreateTableSqlByTableName($tableName){
        try{
            $tableName = str_replace(' ','',$tableName);
            $sql = 'show create table '.$tableName;
            $res = DB::connection($this->remoteDB)->select($sql);
            $newSql = (array)($res[0]);
            return $newSql['Create Table'];
        }catch(\Exception $e){
            $msg = '';
            if(isset($newSql['Create Table'])){
                $msg = $newSql['Create Table'];
            }
            Log::info($tableName.'创建异常语句'.$msg);
            var_dump($e->getMessage());
            return false;
        }
    }

    //使用sql创建表格
    public function createTableBySql($sql){
        $res = DB::connection($this->localDB)->update($sql);
    }
}
